<template>
  <div>
    <el-form :rules="rules" ref="form" label-width="110px" :model="editData">
      <el-form-item label="质押人类型" prop="gua_entity_type">
        <c-select
          v-model="editData.gua_entity_type"
          class="form-control-ml"
          placeholder="请选择质押人类型"
          :options="enumEntityType"
        ></c-select>
      </el-form-item>

      <el-form-item
        :label="
          isCommon
            ? '营业执照OCR识别(请上传清晰的图片，以确保识别准确性，非必填)'
            : '身份证头像页OCR识别(请上传清晰的图片，以确保识别准确性，非必填)'
        "
      >
        <upload-oss
          single-image
          :dir="dir"
          ref="stockUpload"
          accept="image/*"
          :file-name="0"
          :file-list="registerList"
          :on-change="registerChange"
          :on-complete="handleAttachComplete"
        ></upload-oss>
      </el-form-item>

      <el-form-item
        :label="+editData.gua_entity_type === 1 ? '出质公司名称' : '出质人名称'"
        prop="gua_entity_corp"
      >
        <el-input
          v-model="editData.gua_entity_corp"
          class="form-control-ml"
          placeholder="请输入出质人名称"
        ></el-input>
      </el-form-item>

      <el-form-item label="证件号" prop="gua_entity_cert_no">
        <el-input
          v-model="editData.gua_entity_cert_no"
          class="form-control-ml"
          placeholder="请输入身份证号/营业执照号"
        ></el-input>
      </el-form-item>
      <el-form-item label="联系电话" prop="gua_entity_mobile">
        <el-input
          v-model="editData.gua_entity_mobile"
          class="form-control-ml"
          placeholder="请输入法人联系电话"
        ></el-input>
      </el-form-item>
      <el-form-item label="出质人地址" prop="gua_entity_address">
        <el-input
          v-model="editData.gua_entity_address"
          class="form-control-ml"
          placeholder="请输入出质人地址"
        ></el-input>
      </el-form-item>
      <el-form-item label="股权所在公司" prop="gua_entity">
        <el-input
          v-model="editData.gua_entity"
          class="form-control-ml"
          placeholder="请输入股权所在公司名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="营业执照" prop="pledge_register_no">
        <el-input
          v-model="editData.pledge_register_no"
          class="form-control-ml"
          placeholder="请输入营业执照"
        ></el-input>
      </el-form-item>
      <el-form-item label="注册资本" prop="pledge_register_capital">
        <el-input
          v-input-number="{ min: 0, fixed: 4 }"
          v-model="editData.pledge_register_capital"
          class="form-control-ml"
          placeholder="请输入公司注册资本"
        >
          <span slot="append">万元</span>
        </el-input>
      </el-form-item>
      <el-form-item label="持股比例" prop="pledge_stock" v-if="+this.guaMethodSub !== 3">
        <el-input
          v-input-number="{ min: 0, fixed: 2, max: 100 }"
          v-model="editData.pledge_stock"
          class="form-control-ml"
          placeholder="请输入持股比例"
        >
          <span slot="append">%</span>
        </el-input>
      </el-form-item>
      <el-form-item :label="+guaMethodSub === 3 ? '入股金额' : '出资额'" prop="pledge_funds">
        <el-input
          v-input-number="{ min: 0, fixed: 4 }"
          v-model="editData.pledge_funds"
          class="form-control-ml"
          :placeholder="+guaMethodSub === 3 ? '请输入入股金额' : '请输入出资额'"
        >
          <span slot="append">万元</span>
        </el-input>
      </el-form-item>
      <el-form-item label="本次出质股权" prop="pledge_equity" v-if="+this.guaMethodSub !== 3">
        <el-input
          v-input-number="{ min: 0, fixed: 2, max: 100 }"
          v-model="editData.pledge_equity"
          class="form-control-ml"
          placeholder="请输入本次出质股权"
        >
          <span slot="append">%</span>
        </el-input>
      </el-form-item>
      <el-form-item label="本次出质额度" prop="pledge_funds_cur">
        <el-input
          v-input-number="{ min: 0, fixed: 4 }"
          v-model="editData.pledge_funds_cur"
          class="form-control-ml"
          placeholder="请输入本次出质额度"
        >
          <span slot="append">万元</span>
        </el-input>
      </el-form-item>
      <el-form-item label="质押开始时间" prop="pledge_start_date">
        <el-date-picker
          class="form-control-ml"
          v-model="editData.pledge_start_date"
          placeholder="请选择质押开始时间"
          type="date"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="质押结束时间" prop="pledge_end_date">
        <el-date-picker
          class="form-control-ml"
          v-model="editData.pledge_end_date"
          placeholder="请选择质押结束时间"
          type="date"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="合同共计">
        <el-input
          class="form-control-ml"
          v-model="editData.num_copes_lower"
          placeholder="合同共计"
          v-input-number="{ min: 0, fixed: 0 }"
        >
          <span slot="append">份</span>
        </el-input>
      </el-form-item>
      <el-form-item label="甲乙双方各执">
        <el-input
          class="form-control-ml"
          v-model="editData.num_copes_per_lower"
          placeholder="甲乙双方各执"
          v-input-number="{ min: 0, fixed: 0 }"
        >
          <span slot="append">份</span>
        </el-input>
      </el-form-item>
      <el-form-item label="是否加盖公章" v-if="isSYSTEM || isRedo">
        <c-select
          class="form-control-ml"
          :options="{
            0: '不盖章(客户线下签约时选择)',
            1: '加盖公章',
          }"
          :number-key="true"
          v-model="signStatus"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <el-button class="btn-long" type="primary" @click="submit" :loading="saveLoading">
          保存
        </el-button>
        <el-button class="btn-long" @click="beforeClose" :loading="saveLoading">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mobileValidator } from '@/common/plugins/validator'
import {
  idCardValidate,
  licenseValidate,
  nzhToMoney,
  nzhToNum,
  arrayToString,
  arrayFromString,
} from '@vimi/utils-tool'
import { mapGetters } from 'vuex'
import { enumEntityType } from '@/credit/views/county/unionProvince/components/ContractGuardMortgage'
import { getIdCard, getOrgInfo } from '@/credit/views/city/program/ocr/index'
export default {
  components: {},
  props: {
    tableId: { type: String, default: '' },
    isRedo: {
      // 是否合同重做，
      type: Boolean,
      default: false,
    },
    relatedData: {
      type: Object,
      default: () => ({}),
    },
    formData: {
      type: Object,
      default: () => ({}),
    },
    guaMethodSub: {
      type: String,
      default: '0',
    },
  },
  data() {
    const certNoValidator = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else if (+this.editData.gua_entity_type === 1 && !licenseValidate(value)) {
        callback(new Error('错误的营业执照号，请重新输入'))
      } else if (+this.editData.gua_entity_type !== 1 && !idCardValidate(value)) {
        callback(new Error('错误的身份证号，请重新输入'))
      } else {
        callback()
      }
    }
    return {
      enumEntityType,
      editData: {
        gua_entity_cert_no: '',
        gua_entity_corp: '',
        gua_entity_address: '',
        gua_entity_type: '2',
      },
      loading: false,
      tableName: 'gua_contract',
      saveLoading: false,
      rules: {
        gua_entity_type: { required: true, message: '请选择质押人类型', trigger: 'change' },
        gua_entity_corp: { required: true, message: '请输入出质人名称', trigger: 'blur' },
        gua_entity_mobile: [
          { required: true, message: '请输入法人联系电话', trigger: 'blur' },
          { validator: mobileValidator, message: '请输入正确的电话号码', trigger: 'blur' },
        ],
        gua_entity_address: [{ required: true, message: '请输入出质人地址', trigger: 'blur' }],
        // sign_address: [{ required: true, message: '请输入签约地点', trigger: 'blur' }],
        gua_entity_cert_no: [
          { required: true, message: '请输入身份证号/营业执照号', trigger: 'blur' },
          { validator: certNoValidator, trigger: 'blur' },
        ],
        gua_entity: { required: true, message: '请输入股权所在公司名称', trigger: 'blur' },
        pledge_register_no: [
          { required: true, message: '请输入营业执照号', trigger: 'blur' },
          { validator: this.registerNoValidator, trigger: 'blur' },
        ],
        pledge_register_capital: {
          required: true,
          message: '请输入公司注册资本',
          trigger: 'blur',
        },
        pledge_stock: { required: true, message: '请输入持股比例', trigger: 'blur' },
        pledge_funds:
          +this.guaMethodSub === 3
            ? { required: true, message: '请输入入股金额', trigger: 'blur' }
            : { required: true, message: '请输入出资额', trigger: 'blur' },
        pledge_equity: { required: true, message: '请输入本次出质股权', trigger: 'blur' },
        pledge_funds_cur: { required: true, message: '请输入本次出质额度', trigger: 'blur' },
        pledge_start_date: { required: true, message: '请输入质押开始时间', trigger: 'change' },
        pledge_end_date: { required: true, message: '请输入质押结束时间', trigger: 'change' },
      },
      registerList: [],
      signStatus: 1,
    }
  },
  computed: {
    ...mapGetters(['entrustContract', 'org']),
    dir() {
      return `credit/contract/pledge/stock/${this.queryId}`
    },
    queryId() {
      return this.relatedData.customer_related_id
    },
    isCommon() {
      return +this.editData.gua_entity_type === 1
    },
    isSYSTEM() {
      // 系统后台重做合同
      return this.org.orgClass === 'org_credit_sys'
    },
  },
  watch: {
    formData: {
      handler: function () {
        this.init()
      },
      deep: true,
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    handleAttachComplete(files) {
      this.editData.cert_attachment = arrayToString(files.map(it => it.url))
      this.onSubmit()
    },
    registerChange(file) {
      if (!file || !file.raw) {
        return
      }
      this.ocrFile = file.raw
      this.loading = true
      if (this.isCommon) {
        getOrgInfo(this.ocrFile)
          .then(res => {
            const data = res?.data ?? {}
            this.editData.gua_entity_cert_no = data.reg_num || ''
            this.editData.gua_entity_corp = data.name
            this.editData.gua_entity_address = data.address
          })
          .finally(() => {
            this.loading = false
          })
      } else {
        getIdCard(this.ocrFile, true)
          .then(res => {
            const data = res?.data ?? {}
            this.editData.gua_entity_cert_no = data.num || ''
            this.editData.gua_entity_corp = data.name
            this.editData.gua_entity_address = data.address
          })
          .finally(() => {
            this.loading = false
          })
      }
    },
    init() {
      this.editData = {
        ...this.formData,
        pledge_start_date: this.formData.pledge_start_date || '',
        pledge_end_date: this.formData.pledge_end_date || '',
        gua_entity_type: this.formData.gua_entity_type || '2',
        gua_entity_cert_no: this.formData.gua_entity_cert_no || '',
        gua_entity_corp: this.formData.gua_entity_corp || '',
        gua_entity_address: this.formData.gua_entity_address || '',
      }
      this.editData.pledge_start_date = this.getDateFormat(this.editData.pledge_start_date)
      this.editData.pledge_end_date = this.getDateFormat(this.editData.pledge_end_date)

      const attach = arrayFromString(this.formData.cert_attachment)
      this.registerList = attach.length ? [{ url: attach?.[0] ?? '' }] : []
    },
    idCardValidator(rule, value, callback) {
      if (value === '') {
        callback()
      } else if (!idCardValidate(value)) {
        callback(new Error('错误的身份证号，请重新输入'))
      } else {
        callback()
      }
    },
    registerNoValidator(rule, value, callback) {
      if (value === '') {
        callback()
      } else if (!licenseValidate(value)) {
        callback(new Error('营业执照号格式错误，请重新输入'))
      } else {
        callback()
      }
    },
    getDateFormat(value) {
      if (!value) {
        return ''
      }
      const str = value.replace(/^(\d+).(\d+).(\d+).*/, '$1/$2/$3')
      return new Date(str)
    },
    handleBeforeSave(model) {
      model.gua_entity_corp = model.gua_entity_corp.replace(/\s*/g, '')
      model.gua_entity = model.gua_entity.replace(/\s*/g, '')
      model.pledge_start_date = this.$utils.dateFormat(model.pledge_start_date, 'yyyy年MM月dd日')
      model.pledge_end_date = this.$utils.dateFormat(model.pledge_end_date, 'yyyy年MM月dd日')
      model.pledge_funds_capital = nzhToMoney(model.pledge_funds * 10000)
      model.customer_name = this.relatedData.customer_name
      model.customer_address = this.relatedData.address
      model.customer_phone = this.relatedData.mobile_no
      model.bank_name = this.entrustContract.bank_name
      model.entrust_bank_name = this.entrustContract.entrust_bank_name
      model.apply_funds = this.entrustContract.reply_funds
      model.loan_contract_no = this.entrustContract.loan_contract_no
      model.ensure_contract_no = this.entrustContract.ensure_contract_no
      // model.ensure_contract_name = this.entrustContract.ensure_contract_name
      model.gua_com_corp = this.entrustContract.accept_entrust_entity_corp
      model.customer_related_id = this.queryId
      model.num_copes_per = model.num_copes_per_lower ? nzhToNum(model.num_copes_per_lower) : ''
      model.num_copes = model.num_copes_lower ? nzhToNum(model.num_copes_lower) : ''
      model.gua_method = 2
      model.gua_method_sub = this.guaMethodSub || 0
      return model
    },
    submit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$refs.stockUpload.submit()
        } else {
          this.$message.error('输入错误，请重新输入！')
        }
      })
    },
    onSubmit() {
      if (this.tableId) {
        this.putData()
      } else {
        this.postData()
      }
    },
    putData() {
      if (!this.queryId) {
        return
      }
      const data = this.handleBeforeSave(this.editData)
      if (this.isSYSTEM || this.isRedo) {
        //系统后台重做重签合同
        data.sign_status = this.signStatus
        data.re_sign_type = 1
      }
      data.sign_date = this.$utils.dateFormat(new Date(), 'yyyy年MM月dd日')
      this.saveLoading = true
      this.$api
        .updateData(this.$serviceName, this.tableName, this.tableId, data)
        .then(() => {
          this.handleSuccess()
        })
        .catch(err => {
          this.$message.error(err?.data?.error_description || '提交失败，请重试！')
        })
        .finally(() => {
          this.saveLoading = false
        })
    },
    handleSuccess() {
      this.init()
      this.$emit('success', true)
      this.$message.success('保存成功')
    },
    postData() {
      if (!this.queryId) {
        return
      }
      this.saveLoading = true
      const data = this.handleBeforeSave(this.editData)
      if (this.isSYSTEM || this.isRedo) {
        //系统后台重做重签合同
        data.sign_status = this.signStatus
        data.re_sign_type = 2
      }
      data.sign_date = this.$utils.dateFormat(new Date(), 'yyyy年MM月dd日')
      this.$api
        .addData(this.$serviceName, this.tableName, data)
        .then(() => {
          this.handleSuccess()
        })
        .catch(err => {
          this.$message.error(err?.data?.error_description || '提交失败，请重试！')
        })
        .finally(() => {
          this.saveLoading = false
        })
    },
    beforeClose() {
      this.$refs.form.clearValidate()
      this.$emit('close', false)
    },
  },
}
</script>

<style lang="scss" scoped></style>
